<script setup>
// CPV分析(客户提货量完成率)
import { ref, onMounted } from 'vue'

const convertData = apiData => {
	// 动态生成坐标轴标签
	const brands = [...new Set(apiData.map(item => item.brand))]
	const dates = [...new Set(apiData.map(item => item.statisticDate))]
	return apiData.map(item => {
		return [brands.indexOf(item.brand), dates.indexOf(item.statisticDate), item.completionRate.toFixed(1)]
	})
}

const fetchData = async () => {
	try {
		const response = await fetch('http://localhost/api/ads-cpv')
		const apiData = await response.json()
		// 更新坐标轴标签和系列数据
		chartOption.value.xAxis.data = [...new Set(apiData.map(item => item.brand))]
		chartOption.value.yAxis.data = [...new Set(apiData.map(item => item.statisticDate))]
		chartOption.value.series[0].data = convertData(apiData)
	} catch (error) {
		console.error('数据获取失败:', error)
	}
}

onMounted(() => {
	fetchData()
})

const chartOption = ref({
	backgroundColor: 'transparent',
	tooltip: {
		position: 'top',
	},
	grid: {
		top: '10%',
		left: '5%',
		right: '12%',
		bottom: '8%',
		containLabel: true,
	},
	xAxis: {
		type: 'category',
		data: [],
		splitArea: {
			show: true,
		},
	},
	yAxis: {
		type: 'category',
		data: [],
		splitArea: {
			show: true,
		},
	},
	visualMap: {
		min: 60,
		max: 150,
		calculable: true,
		orient: 'vertical',
		top: 'center',
		right: '2%',
		textStyle: {
			color: '#fff',
			fontWeight: 'bold',
		},
	},
	series: [
		{
			name: 'CPV完成率',
			type: 'heatmap',
			data: [
				[0, 0, 1.4], // [x, y, value]
				[0, 1, 1.54],
				[0, 2, 1.24],
			],
			label: {
				show: true,
			},
			emphasis: {
				itemStyle: {
					shadowBlur: 10,
					shadowColor: 'rgba(0, 0, 0, 0.5)',
				},
			},
		},
	],
})
</script>

<template>
	<v-chart theme="chalk" :option="chartOption" />
</template>

<style scoped></style>
